package ar.com.tallerdos.smartdinner.sync;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import ar.com.tallerdos.smartdinner.cocina.MainActivity;
import ar.com.tallerdos.smartdinner.db.DatabaseHelper;
import ar.com.tallerdos.smartdinner.model.Product;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.j256.ormlite.table.TableUtils;

public class Sincronizador extends AsyncTask<Void, Void, Void> {
	
	private static final String SERVER_URL = "http://10.0.2.2/cake_2_4_6";//"http://192.168.0.51/prueba";
	private static final String COCINA_SERVICE = "consultarCocina.php";

	ProgressDialog pdLoading;
	MainActivity activity;
	
	public Sincronizador(MainActivity mainActivity) {
		activity = mainActivity;
		pdLoading = new ProgressDialog(mainActivity);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		// this method will be running on UI thread
		pdLoading.setMessage("\tLoading...");
		pdLoading.show();
	}

	@Override
	protected Void doInBackground(Void... params) {
		
		String productosJson = llamarWebService(SERVER_URL + "/" + COCINA_SERVICE);
		
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		
		List<Product> productos =  gson.fromJson(productosJson, new TypeToken<List<Product>>(){}.getType());
	
		DatabaseHelper databaseHelper = new DatabaseHelper(activity.getApplicationContext());
		try {
			TableUtils.clearTable(databaseHelper.getConnectionSource(), Product.class);
			for (Product prd : productos) {
				databaseHelper.getProductRuntimeExceptionDao().create(prd);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
			
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		// this method will be running on UI thread
		super.onPostExecute(result);
		pdLoading.dismiss();
	}

	private String llamarWebService(String url) {
		InputStream is = null;

		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			Log.e("log_tag", "Conexion exitosa");
		} catch (Exception e) {
			Log.e("log_tag", "Error en conexion http" + e.toString());
		}

		return convertToString(is);
	}

	public String convertToString(InputStream is) {
		// convert response to string
		String result = "";

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();

			result = sb.toString();
			Log.e("log_tag",
					"Conversion Exitosa del resultado" + result.toString());
		} catch (Exception e) {
			Log.e("log_tag",
					"Error en conversion del resultado " + e.toString());
		}

		return result;
	}

}
